package org.vectrics.recruiter.data;

import java.io.File;
import java.io.FileInputStream;
import java.util.Collection;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.vectrics.SystemException;
import org.vectrics.common.util.FileUtil;
import org.vectrics.config.MailConfiguration;
import org.vectrics.domain.Domain;
import org.vectrics.mail.MailMessage;
import org.vectrics.mail.UserMailer;
import org.vectrics.provider.CoreServiceLocator;
import org.vectrics.recruiter.RecruitServiceLocator;
import org.vectrics.recruiter.config.RecruitConfig;
import org.vectrics.recruiter.job.Job;
import org.vectrics.recruiter.user.CandidateInfo;
import org.vectrics.user.ContactInfo;
import org.vectrics.user.Person;

public class SampleResumeEmailer {
    private transient Logger log = Logger.getLogger(this.getClass());

    public SampleResumeEmailer() {
        super();
    }

    public void sendEmailedResumes(Job job) {
        MailConfiguration mailConfig = CoreServiceLocator.getConfiguration().getFromMailConfiguration(job.getDomain());
        File rootDirectory = new File("./test/test-resumes/email-resumes");
        File[] files = rootDirectory.listFiles();
        Person resumeReceiver = getTestResumeReceiver(job.getDomain());
        int possibleResumeCount = files.length;
        for (int i = 0; i < possibleResumeCount; i++) {
            File directory = files[i];
            if ((directory.isDirectory()) && (directory.getName().indexOf("CVS") > 0)) {
                createEmailFromResumeDirectory(resumeReceiver, directory, mailConfig, job);
            }
        }
    }

    public void createEmailFromResumeDirectory(Person resumeReceiver, File directory, MailConfiguration mailConfig,
            Job job) {
        String firstName = null;
        String lastName = null;
        String email = null;
        String subject = null;
        try {
            FileInputStream propFile = new FileInputStream(directory + "/test.properties");
            Properties testProperties = new Properties();
            testProperties.load(propFile);
            firstName = testProperties.getProperty("first.name");
            lastName = testProperties.getProperty("last.name");
            email = testProperties.getProperty("email");
            subject = testProperties.getProperty("email.subject") + " Job: " + job.getReferenceId();
            propFile.close();
        } catch (Exception ex) {
            log.error("Exception reading property file", ex);
        }
        String body = FileUtil.getFileContents(directory + "/cover-letter.txt");

        log.debug("Make a couple people that have similar names, for testing name matching for email processing");
        Person person1 = new Person();
        person1.setFirstName(firstName);
        person1.setLastName(lastName);
        person1.setMiddleName("T.");
        person1.setLocale("en");
        person1.setDomain(job.getDomain());
        CoreServiceLocator.getPersonService().updatePerson(person1);

        CandidateInfo candidate1 = RecruitServiceLocator.getRecruitUserService().createCandidateInfoIfNotExist(person1);
        RecruitServiceLocator.getRecruitUserService().updateCandidateInfo(candidate1);

        ContactInfo contactInfo = person1.createContactInfoIfNotExist();
        contactInfo.setEmail(email);
        CoreServiceLocator.getPersonService().updatePerson(person1);

        Person person2 = new Person();
        person2.setFirstName(firstName);
        person2.setLastName(lastName);
        person2.setMiddleName(null);
        person2.setLocale("en");
        person2.setDomain(job.getDomain());
        CoreServiceLocator.getPersonService().updatePerson(person2);

        UserMailer mailer = new UserMailer(mailConfig);
        Person recipient = resumeReceiver;
        MailMessage mailMessage = new MailMessage(job.getDomain());
        mailMessage.setBody(body);
        mailMessage.setSubject(subject);

        mailMessage.setFromAddress(email);
        mailMessage.setFromName(firstName + " " + lastName);
        mailMessage.addAttachmentFile(directory + "/resume.doc");
        mailer.sendMessage(recipient, mailMessage);
    }

    public static Person getTestResumeReceiver(Domain domain) {
        if (domain == null) {
            throw new SystemException("getTestResumeReceiver(domain) was passed a null domain");
        }

        String testResumeEmailAddress = RecruitConfig.getRecruitInstance().getResumeRecipientEmailAddress(domain);

        Person resumeReceiver = null;
        Collection persons = CoreServiceLocator.getPersonService().findPersonsWithEMail(domain, testResumeEmailAddress);
        if (persons.isEmpty()) {
            resumeReceiver = CoreServiceLocator.getPersonService().findCreatePersonWithUserName(domain,
                    "resume_recipient");
            resumeReceiver.setFirstName("emailed_resume");
            resumeReceiver.setLastName("recipient");
            resumeReceiver.setLocale("en");
            resumeReceiver.createContactInfoIfNotExist().setEmail(testResumeEmailAddress);
            CoreServiceLocator.getPersonService().updatePerson(resumeReceiver);
        } else {
            resumeReceiver = (Person) persons.iterator().next();
        }
        if (resumeReceiver == null) {
            throw new SystemException("Resume receiver is null");
        }
        return (resumeReceiver);
    }

}
